package cn.lupin.controller;

import cn.lupin.pojo.Users;
import cn.lupin.pojo.UsersVO;
import cn.lupin.pojo.WxLogin;
import cn.lupin.service.UserService;
import cn.lupin.utils.HttpUtils;
import cn.lupin.utils.LaughJSONResult;
import cn.lupin.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

@RestController
@Api(value = "用户注册登录的接口", tags = {"注册和登录的controller"})
public class RegistLoginController extends BasicController {

    @Autowired
    private UserService userService;

    @Value("${wx.xcc.appid:}")
    private String appId;

    @Value("${wx.xcc.appsecret}")
    private String appSecret;

    @PostMapping("/regist")
    @ApiOperation(value = "用户注册", notes = "用户注册的接口")
    public LaughJSONResult regist(@RequestBody Users user) throws Exception {
        // 1. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return LaughJSONResult.errorMsg("用户名和密码不能为空");
        }

        // 2. 判断用户名是否存在
        boolean usernameIsExist = userService.queryUsernameIsExist(user.getUsername());

        // 3. 保存用户，注册信息
        if (!usernameIsExist) {
            user.setNickname(user.getUsername());
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            user.setFansCounts(0);
            user.setReceiveLikeCounts(0);
            user.setFollowCounts(0);
            userService.saveUser(user);
        } else {
            return LaughJSONResult.errorMsg("用户名已经存在，请换一个再试");
        }
        user.setPassword("");
        UsersVO usersVO = setUserRedisSessionToken(user);
        return LaughJSONResult.ok(usersVO);
    }

    @ApiOperation(value = "用户登录", notes = "用户登录的接口")
    @PostMapping("/login")
    public LaughJSONResult login(@RequestBody Users user) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        // 1. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return LaughJSONResult.errorMsg("用户名或密码不能为空...");
        }
        // 2. 判断用户是否存在
        Users userResult = userService.queryUserForLogin(username,
                MD5Utils.getMD5Str(user.getPassword()));
        // 3. 返回
        if (userResult != null) {
            userResult.setPassword("");
            UsersVO usersVO = setUserRedisSessionToken(userResult);
            return LaughJSONResult.ok(usersVO);
        } else {
            return LaughJSONResult.errorMsg("用户名或密码不正确, 请重试...");
        }
    }

    @ApiOperation(value = "用户注销", notes = "用户注销的接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true,
            dataType = "string", paramType = "query")
    @PostMapping("/logout")
    public LaughJSONResult logout(String userId) throws Exception {
        redis.del(USER_REDIS_SESSION + ":" + userId);
        return LaughJSONResult.ok();
    }

    @ApiOperation(value = "微信账号登录", notes = "微信账号登录的接口")
    @PostMapping("/wxlogin")
    public LaughJSONResult wxLogin(@RequestBody WxLogin wxLogin) throws Exception {
        String code = wxLogin.getCode();
        // 1. 判断登录凭证必须不为空
        if (StringUtils.isBlank(code)) {
            return LaughJSONResult.errorMsg("用户登录凭证不能为空...");
        }
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId,
                appSecret,
                code
        );
        Map<String, String> result = HttpUtils.doHttpGetWx(url);
        String openId = result.get("openid");
        String session_key = result.get("session_key");
        // 2. 查询用户
        Users user = userService.queryUserByUserName(openId);
        // 3. 保存用户，注册信息
        if (user == null) {
            user = new Users();
            user.setUsername(openId);
            user.setNickname("用户" + openId);
            user.setPassword(MD5Utils.getMD5Str(session_key));
            user.setFansCounts(0);
            user.setReceiveLikeCounts(0);
            user.setFollowCounts(0);
            userService.saveUser(user);
        }
        user.setPassword("");
        UsersVO usersVO = setUserRedisSessionToken(user);
        return LaughJSONResult.ok(usersVO);
    }

    private UsersVO setUserRedisSessionToken(Users user) {
        String uniqueToken = UUID.randomUUID().toString();
        redis.set(USER_REDIS_SESSION + ":" + user.getId(), uniqueToken, 1000 * 60 * 30);
        UsersVO usersVO = new UsersVO();
        usersVO.setUser(user);
        usersVO.setUserToken(uniqueToken);
        return usersVO;
    }
}
